#include "http_file_download.h"
#include <iostream>
using namespace std;
using namespace bestv;


void downloadFunc(void* param) {
	bestv::BtvUInt64 startIndex(0, 0);
	bestv::HttpFileDownload* httpFileDownload = reinterpret_cast<HttpFileDownload*>(param);
	HttpFileDownload::statusT status;
	bestv::BtvUInt64 downloadedBytes;
	btvClockT startTime;
	
	startTime =  btvapiTimeNow();
	
	if(httpFileDownload->start()== 0) {
		printf("Downloading...\n");
		do{
			status = httpFileDownload->downloadDataChunk();	
		}
		while(status == HttpFileDownload::DOWNLOAD_NOT_FINISHED);
	}

	downloadedBytes = httpFileDownload->getNumberOfDownloadedBytes();
	btvClockT stopTime =  btvapiTimeNow();
	btvClockT ellapsedTime = btvapiTimeMinus(startTime, stopTime);
	/*
		Calculation valid only
		for files smaller than 2 GB.
		Good enough for the tests.
	*/
	int bytes = downloadedBytes.getL();

	double bitrate = (8. * bytes * btvapiClocksPerSec()) / ellapsedTime;

	printf("Downloaded bytes %d MB\n", bytes/1000000);
	printf("Average bitrate %d Mbit/s\n", (int)(bitrate/1000000));
}

void main(){
	BandwidthManager::getInstance().setInitialSharedBandwidth(15000000);
	BandwidthManager::getInstance().setHighBandwidthShare(0.8);
		
	bestv::BtvUInt64 startIndex(0, 0);

	bestv::BtvString almost2GUrl("http://10.18.4.113/almost2G.ts"); 
	//bestv::BtvString almost2GUrl("http://127.0.0.1/almost2G.ts"); 
	//bestv::BtvString almost2GUrl("http://127.0.0.1/300MB.ts"); 
	bestv::BtvString constantBwFilename("constantBwFilename.ts");

	if(1) {
		//*********************
		//One download Forever!
		//*********************
		while(1){
			bestv::HttpFileDownload *httpFileDownload = new HttpFileDownload(almost2GUrl, 
				constantBwFilename, 
				BandwidthManager::HIGH_PRIORITY, 
				startIndex);

			downloadFunc(httpFileDownload);
			httpFileDownload->stop();
			delete httpFileDownload;
		}
		
	}

}